/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.job;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.log4j.Logger;

import jp.aist.gtrc.plus.scheduler.SchedulerOptions;
import jp.aist.gtrc.plus.scheduler.specific.pbs.status.PBSJobStatus;
import jp.aist.gtrc.plus.scheduler.status.JobID;
import jp.aist.gtrc.plus.scheduler.status.JobStatus;
import jp.aist.gtrc.plus.scheduler.job.FairshareSortKey;
import jp.aist.gtrc.plus.scheduler.job.JobStateType;



public class FairshareScheduler extends SortScheduler {

        public static final int HALF_LIFE = 3*60; // seconds

        protected static final Logger logger = Logger.getLogger(FairshareScheduler.class);

        private Collection<JobStatus> lastRunningJobs = new ArrayList<JobStatus>();
        private long lastDecayTime = System.currentTimeMillis();
        private Map<String,Integer> cpuUsage = new HashMap<String,Integer>();

	public FairshareScheduler() {

		super();

	}

	public void init(SchedulerOptions options) {

                logger.debug("FairshareScheduler init()");
		// sort jobs by submit time
		// ignore queue priority, only check job priority.
		addJobSortKey(new FairshareSortKey(this));
                addJobSortKey(JobSortKey.PBSJobID);


	}

        public void updateStatus(Collection<JobStatus> allJobs) {
          
           long currentTime = System.currentTimeMillis();  
           while (currentTime - lastDecayTime > HALF_LIFE*1000) {
              decay(); 
              lastDecayTime = lastDecayTime + HALF_LIFE*1000;
           }

           Map<String,JobStatus> runningJobs = getRunningJobs(allJobs);

           for (JobStatus jobStatus : lastRunningJobs) {
              JobStatus runningJob = runningJobs.get(jobStatus.getJobID().toString()); 
              if (runningJob != null) {
                 int deltaUsage = ((PBSJobStatus) runningJob).getUsedCPUTime() - ((PBSJobStatus) jobStatus).getUsedCPUTime();
                 String owner = jobStatus.getOwner();
                 Integer usage = cpuUsage.get(owner);
                 if (usage == null) {
                    usage = new Integer(0);
                 }
                 int newUsage = usage + deltaUsage;
                 cpuUsage.put(owner,newUsage);
 //System.out.println(new Date() + " update " + owner + "=" + newUsage);
              }

           }              
           lastRunningJobs = runningJobs.values();      
           
        }

        private Map<String,JobStatus> getRunningJobs(Collection<JobStatus> allJobs) {
           Map<String,JobStatus> runningJobs = new HashMap<String,JobStatus>();
           for (JobStatus jobStatus : allJobs) {
              if (jobStatus.getState() == JobStateType.Running)
                 runningJobs.put(jobStatus.getJobID().toString(),jobStatus); 
           }
           return runningJobs;
        }

        private void decay() {
int t = (int) (System.currentTimeMillis()/1000);
           for (String owner : cpuUsage.keySet()) {
//System.out.println(t + "  " + owner + " " + cpuUsage.get(owner));
              int usage = cpuUsage.get(owner)/2;
              cpuUsage.put(owner,usage);
//System.out.println("decay " + owner + "=" + usage);
           }
        }

        public Map<String,Integer> getCPUUsageMap() {
           return cpuUsage;
        }

}

